package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.utils.Error;
import com.tomkk.utils.Success;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Tomkk on 2016/5/25.
 */
@WebServlet(name = "UploadServlet",urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        long maxSize = 5*1024*1024L;
        Gson gson = new Gson();
        String json = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(20*1024);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List formlists = null;
            try {
                formlists = (List)upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = formlists.iterator();
            while(iter.hasNext()) {
                FileItem fileItem = (FileItem) iter.next();
                String fileName = fileItem.getName();
                String[] res = fileName.split("\\.");
                //文件后缀名
                String ext = res[res.length - 1];
                long fileSize = fileItem.getSize();
                if (((fileName == null) || (fileName.equals(""))) || (fileSize == 0)) {
                    json = gson.toJson(new Error(1, "文件不能为空"));
                    PrintWriter writer = response.getWriter();
                    writer.print(json);
                    writer.flush();
                    return;
                } else if (fileSize > maxSize) {
                    json = gson.toJson(new Error(1, "文件大小不应该超过5M"));
                    PrintWriter writer = response.getWriter();
                    writer.print(json);
                    writer.flush();
                    return;
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                //新文件名为年月日小时分钟秒加五位随机数
                String newName = simpleDateFormat.format(new Date());
                //相对路径
                //TODO 部署修改
                String relPath = "/upload/headimage/" + newName + "." + ext;
                //绝对路径
                String uploadDirPath = getServletContext().getRealPath("upload")+"/headimage";
                String realPath = uploadDirPath + "/" + newName + "." + ext;
                File saveFile = new File(realPath);
                try {
                    fileItem.write(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    json = gson.toJson(new Error(2,realPath));
                    PrintWriter writer = response.getWriter();
                    writer.print(json);
                    writer.flush();
                    return;
                }
                //上传成功,返回相对地址
                json = gson.toJson(new Success(0, relPath));
                PrintWriter writer = response.getWriter();
                writer.print(json);
                writer.flush();
            }
        }else{
            json = gson.toJson(new Error(0,"文件格式错误"));
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.flush();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
